<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css" type="text/css"/> 
</head>
<body>
	<div id="icons">
	</div>
	<br>
	<input id="qsInput" type="text" onKeyPress="handleKeyEvents();"/>
	<div class="right">
		<a id="selectedTitle" href="javascript:void(0);" onclick = "doSearch();"></a>
	</div>
	<div>
		<a id="lnkCustomize" href="javascript:void(0);" onclick = "showHideSettings();">Show settings</a>
	</div>

	<div id="settings" class="hidden">
		<table width="100%">
			<tr>
				<td>
					ID:
				</td>
				<td>
					<span id="fldId"></span>
				</td>
			</tr>
			<tr>
				<td>
					Title:
				</td>
				<td>
					<input id="fldTitle" type="text"/>
				</td>
			</tr>
			<tr>
				<td>
					Url:
				</td>
				<td>
					<input id="fldUrl" type="text"/>
					<span class="help">Search keywords will be appended to the end of Url.</span>
				</td>
			</tr>
		</table>
		<div class="right actions">			
			<a id="lnkAdd" href="javascript:void(0);" onclick = "addNewEngine();" style="float:left;">Add</a>
			<a id="lnkDelete" href="javascript:void(0);" onclick = "deleteEngine();" style="float:left;">Delete</a>
			<a id="lnkUpdate" href="javascript:void(0);" onclick = "updateSettings();">Update</a>
		</div>
		<div class="center"><a href="" onclick="openInNewTab('http://chrome-quick-search.googlecode.com')" title="Navigate to project page">v0.3</a></div>
	</div>		
	<script language="javascript">
		
		//Constants
		var STORAGE_ID = "quickSearch";
		var CUSTOM_IMAGE_PATH = "images/custom.png";
		var ENGINES_MANIFEST = "ENGINES_MANIFEST";
		var SELECTED_ENGINE = "selectedEngine";
		
		var _enginesList = new Array();
		var _selectedEngineId = "wikipedia";
		var _qsInput = $get("qsInput");
		var _defaultEngineId = "google";
		var _faviconUrl;
		readEngines("engines.json");
		
		function handleKeyboardEvents() {
			if ( event.keyCode == 13 ) doSearch(); // Enter key
		}
		
		function getSelection() {
			chrome.tabs.getSelected(null, function(tab) {
				chrome.tabs.sendRequest(tab.id, {command: "getSelection"}, function(response) {
					_qsInput.value = (response.selection) ? response.selection : "";
				});
			});
		}
		
		function $get(id) {
			return document.getElementById(id);
		}
		
		function $removeAllChildren(id) {
			var element = $get(id);
			if ( element.hasChildNodes() ) {
				while ( element.childNodes.length >= 1 )
				{
					element.removeChild( element.firstChild );       
				} 
			}
		}
		
		function fillFormats() {
			var manifest = getParam(ENGINES_MANIFEST); 
			var engines = manifest.engines;
			_faviconUrl = manifest.faviconUrl;
			$removeAllChildren("icons");
			for (var item in engines) {
				var engine = engines[item];
				_enginesList[engine.id] = engine;
				addEngineIcon(engine);
			}
			var selectedEngine = getParam(SELECTED_ENGINE);
			if (!selectedEngine || !_enginesList[selectedEngine]) {
				selectEngine(manifest.defaultEngine);
			}
			else {
				selectEngine(selectedEngine);
			}
			_qsInput.focus();
			getSelection();
		}
		
		function getParam(name) {
			var param = localStorage[name + "_" + STORAGE_ID];
			if (param) {
				return JSON.parse(param);
			}
			return null;
		}
		
		function setParam(name, value) {
			localStorage[name + "_" + STORAGE_ID] = JSON.stringify(value);
			return getParam(name);
		}
		
		function getIconUrl(url) {
			var domainName = "";			
			var d1 = url.split("://")[1];
			if (d1) {
				domainName = d1.split("?")[0].split("/")[0].split("\\")[0];
			}
			return (domainName.length != 0) ? _faviconUrl + domainName : CUSTOM_IMAGE_PATH; 
		}
		
		function addEngineIcon(engine) {
			var containerDiv = $get("icons");
			var iconDiv = document.createElement("div");
			iconDiv.className = "icon";
			var iconImage = document.createElement("img");
			iconImage.id = engine.id+"_icon";
			//Will show dynamic favIcon if it is custom engine, or it was modified standard
			iconImage.src = (engine.isCustom || engine.isModified) ? getIconUrl(engine.url) : "images/"+engine.id+".png";
			iconImage.title = engine.title;
			iconImage.onclick = function() {
				selectEngine(engine.id);
			}
			iconDiv.appendChild(iconImage);
			containerDiv.appendChild(iconDiv);
		}
		
		function readEngines(url) {
			var enginesManifest = getParam(ENGINES_MANIFEST);
			var xhr = new XMLHttpRequest();
			xhr.open("GET", url, true);
			xhr.send();
			xhr.onreadystatechange = function() {
				if (xhr.readyState == 4) {
					var manifest = JSON.parse(xhr.responseText);
					if (enginesManifest == null) {
						enginesManifest = setParam(ENGINES_MANIFEST, manifest);
					}

					if (enginesManifest.version != manifest.version) {
						mergeManifest(manifest);
					}
					
					fillFormats();
				}
			}
		}
		
		function mergeManifest(manifest) {
			setParam(ENGINES_MANIFEST, manifest);
		}
		
		function selectEngine(selectedEngine) {
			_selectedEngineId = selectedEngine;
			var icon = $get(_selectedEngineId+"_icon");
			clearAllSelection();
			icon.parentElement.className = "selectedIcon";
			setParam(SELECTED_ENGINE, _selectedEngineId);
			$get("selectedTitle").innerText = "Search on " + _enginesList[_selectedEngineId].title;
			if (isSettingsOpened()) {
				populateSettings();
				getSettingsForm()["title"].focus();
			} 
			else {
				_qsInput.focus();
			}
		}
		
		function selectNextEngine() {
			var currentOrder = _enginesList[_selectedEngineId].order;
			for (var item in enginesManifest.engines) {
				if (enginesManifest.engines[item].order > currentOrder) {
					selectEngine(enginesManifest.engines[item].id);
					return;
				}
			}
			selectEngine(manifest.defaultEngine);
		}
		
		function clearAllSelection() {
			for (var eng in _enginesList)	{
				var iconDiv = $get(eng+"_icon");
				if (iconDiv) {
					iconDiv.parentElement.className = "icon";
				}
			}
		}
		
		function doSearch() {
			
			if (_qsInput.value.length == 0) {
				return;
			}
			var searchUrl = _enginesList[_selectedEngineId].url + _qsInput.value;
			openInNewTab(searchUrl);
			_qsInput.value = "";
		}
		
		function openInNewTab(url) {
			chrome.tabs.create({url:url});
		}
		
		function getSettingsForm() {
			var settings = new Array();
			settings["id"] = $get("fldId");
			settings["title"] = $get("fldTitle");
			settings["url"] = $get("fldUrl");
			return settings;
		}
		
		function populateSettings() {
			var currentEngine = _enginesList[_selectedEngineId];
			var settings = getSettingsForm();
			settings["id"].innerText = currentEngine.id;
			settings["title"].value = currentEngine.title;
			settings["url"].value = currentEngine.url;
			settings["title"].focus();
		}
		
		function updateSettings() {
			var settings = getSettingsForm();
			var enginesManifest = getParam(ENGINES_MANIFEST);
			//Append http:// if it was missed
			if (getIconUrl(settings["url"].value) == CUSTOM_IMAGE_PATH) {
				settings["url"].value = "http://" + settings["url"].value;
			}
			for (var item in enginesManifest.engines) {
				if (enginesManifest.engines[item].id == settings["id"].innerText) {
					if (enginesManifest.engines[item].url != settings["url"].value) {
						enginesManifest.engines[item].isModified = true;
					}
					enginesManifest.engines[item].title = settings["title"].value;
					enginesManifest.engines[item].url = settings["url"].value;					
				}
			}
			setParam(ENGINES_MANIFEST, enginesManifest);
			
			showHideSettings();
			fillFormats();
		}
		
		function isSettingsOpened() {
			var settingsDiv = $get("settings");
			return settingsDiv.className != "hidden";
		}
		
		function showHideSettings() {
			var settingsDiv = $get("settings");
			settingsDiv.className = isSettingsOpened() ? "hidden" : "";
			var lnk = $get("lnkCustomize");			
			if (isSettingsOpened()) {
				lnk.innerText = "Hide settings";
				populateSettings();
			}
			else {
				lnk.innerText = "Show settings"; 
				settingsDiv.style.height="0px";
				_qsInput.focus();
			}
		}
		
		function addNewEngine() {
			var enginesManifest = getParam(ENGINES_MANIFEST);
			var count = enginesManifest.engines.length + 1;
			var newId = "custom"+count;
			var newEngine = {id:newId, title:"set title...", url:"http://", order:count, isCustom:true};
			enginesManifest.engines.push(newEngine);
			setParam(ENGINES_MANIFEST, enginesManifest);
			setParam(SELECTED_ENGINE, newId);
			fillFormats();
		}
		
		function deleteEngine() {
			var enginesManifest = getParam(ENGINES_MANIFEST);
			var selectedEngine = getParam(SELECTED_ENGINE);
			var newList = new Array();
			for (var item in enginesManifest.engines) {
				if (enginesManifest.engines[item].id != selectedEngine) {
					newList.push(enginesManifest.engines[item]);
				}
			}
			enginesManifest.engines = newList;
			setParam(ENGINES_MANIFEST, enginesManifest);
			setParam(SELECTED_ENGINE, enginesManifest.defaultEngine);
			fillFormats();
			
		}
	</script>
</body>
</html>